<?php



namespace App\Services\Business\Services;

use App\Services\Business\Interfaces\AppraiseServiceInterface;
use App\Services\Business\Models\Appraise;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;


class AppraiseService implements AppraiseServiceInterface
{

    /**
     * @param int $resource_id
     * @return array
     */
    public function appraises(int $page,int $size,int $resource_id,string $resource_type): array
    {
        $appraises = Appraise::query()
            ->with(['images','user'])
            ->whereResourceId($resource_id)
            ->whereResourceType($resource_type)
            ->orderByDesc('id');
        $total =  $appraises->count();
         $list =  $appraises->forPage($page, $size)->get()->toArray();


        return compact('total','list');
    }

    /**
     * @param int $resourceId
     * @param string $originalContent
     *
     * @return array
     */
    public function create(int $resourceId, string $resourceType, string $originalContent): array
    {
            $comment = Appraise::create([
                'user_id' => Auth::id(),
                'resource_id' => $resourceId,
                'resource_type' => $resourceType,
                'original_content' => $originalContent,
                'render_content' => $originalContent,
            ]);



        return $comment->toArray();
    }

    /**
     * @param int $id
     * @return array
     */
    public function find(int $id): array
    {
        return Appraise::findOrFail($id)->toArray();
    }

    /**
     * @param string $type
     * @param int $resourceId
     * @param array $userIds
     * @return void
     */
    public function changeStatus(string $type, int $resourceId, array $userIds)
    {

        $UserModel = 'App\Services\Member\Models\User' . ucfirst($type);
        $UserModel = new  $UserModel();
        $UserModel::query()->where($type.'_id',$resourceId)->whereIn('user_id',$userIds)->update(['is_appraised'=>1,'appraised_time'=>Carbon::now()]);

    }

    /**
     * @param int $limit
     * @return array
     */
    public function getRecAppraises(int $limit): array
{
   return    Appraise::query()
            ->with(['user'])
            ->where('is_recommend', 1)
            ->limit($limit)
            ->get()
            ->toArray();

    }
}
